package com.wutuo.classroom.provider.dao;

import com.wutuo.classroom.api.request.LearningClassroomRequest;
import com.wutuo.classroom.api.request.ListLearningClassroomRequest;
import com.wutuo.classroom.provider.base.BaseLearningClassroomSqlProvider;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SqlBuilder;

import static org.apache.ibatis.jdbc.SqlBuilder.*;

/**
 * 学堂 dao sql 层
 *
 * @author lvh
 * @version 1.0
 */

public class LearningClassroomSqlProvider extends BaseLearningClassroomSqlProvider {

    public String lisForPage(ListLearningClassroomRequest request) {

        BEGIN();
        getSelected();
        FROM("learning_classroom a ");
        getComonJoin(request);
        SqlBuilder.WHERE(" a.del_flag =  #{delFlag,jdbcType=CHAR}");
        StringBuilder sql = new StringBuilder(SqlBuilder.SQL());
        sql.append(" order by a.create_date desc ");
        if (request.getPage() != null && request.getSize() != null) {
            sql.append(" limit #{index,jdbcType=INTEGER} ,  #{size,jdbcType=INTEGER} ");
        }

        return sql.toString();
    }

    public String list(LearningClassroomRequest request) {

        BEGIN();
        getSelected();
        FROM("learning_classroom a");
        getComonJoin(request);
        SqlBuilder.WHERE(" a.del_flag =  #{delFlag,jdbcType=CHAR}");
        StringBuilder sql = new StringBuilder(SqlBuilder.SQL());
        sql.append(" order by a.create_date desc ");
        return sql.toString();
    }

    public void getSelected() {

        SELECT(
            "a.id,a.learning_type as learningType,user_id as userId,cm_institution_id as cmInstitutionId,learning_title as learningTitle,learning_object as learningObject,teacher as teacher,institution as institution,learning_photo as learningPhoto,page_num as pageNum,recommended_index as recommendedIndex,create_by as createBy,learning_pdf as learningPdf,learning_image as learningImage,learning_office as learningOffice,create_date as createDate,update_by as updateBy,update_date as updateDate,remarks as remarks,del_flag as delFlag,year as year,state as state");
    }

    public void getComonJoin(LearningClassroomRequest request) {

        if (request.getId() != null) {
            SqlBuilder.WHERE(" a.id =#{id}");
        }

        if (request.getIds() != null) {
            SqlBuilder.WHERE(" a.id in (" + request.getIds() + ")");
        }

        if (request.getLearningObject() != null) {
            String[] s = request.getLearningObject().split(",");
            for (int i = 0; i < s.length; i++) {
                SqlBuilder.OR();
                String end = ObjectUtils.toString(s[i], null);
                if (StringUtils.isEmpty(end))
                    continue;
                SqlBuilder.WHERE(" INSTR(a.learning_object," + s[i] + ") > 0");
            }
        }
        SqlBuilder.AND();
    }
}